package com.tron.dobest.java.trongenericity;

import java.util.Arrays;

/**
 * 定义类，要处理的数据类型不确定
 * <E extends Comparable<E>> 参数需要实现comparable接口，可以与同类型比较
 * @param <E>
 */
public class TronArray<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private int size;
    private Object[] elementData;

    public TronArray() {
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    private void ensureCapacity(int minCapacity) {
         int oldCapacity = elementData.length;
        if (oldCapacity >= minCapacity) {
            return;
        }
        int newCapacity = oldCapacity*2;
        if (newCapacity < minCapacity) {
            newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }

    public void add(E e) {
        ensureCapacity(size + 1);
        elementData[size++] = e;
    }

    //此写法定义参数类型
//    public <T extends E> void  addAll(TronArray<T> tronArray) {
//        for (int i = 0; i < tronArray.size(); i++) {
//            add(tronArray.get(i));
//        }
//    }

    //注释方法的简写，此写法定义实例化类型参数
    public  void  addAll(TronArray<? extends E> tronArray) {
        for (int i = 0; i < tronArray.size(); i++) {
            add(tronArray.get(i));
        }
    }

    public E get(int index) {
        return (E) elementData[index];
    }

    public int size() {
        return size;
    }

    public E set(int index, E element) {
        final E e = get(index);
        elementData[index] = element;
        return e;
    }
}
